package com.seo.proxy;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class ReadWriteBuffer {

	private ByteBuffer buffer;

	private int writePosition;

	private int readPosition;

	public ReadWriteBuffer(int size) {
		this.buffer = ByteBuffer.allocateDirect(size);
	}

	public ByteBuffer getBuffer() {
		return buffer;
	}

	public int readToBufferFromChannel(SocketChannel socketChannel) throws IOException {
		buffer.position(writePosition);
		buffer.limit(buffer.capacity());
		int size = socketChannel.read(buffer);
		writePosition = buffer.position();
		return size;
	}

	public int writeFromBufferToChannel(SocketChannel socketChannel) throws IOException {
		buffer.position(readPosition);
		buffer.limit(writePosition);
		int size = socketChannel.write(buffer);
		readPosition = buffer.position();
		return size;
	}

	public boolean isDataAvailable() {
		return writePosition > readPosition;
	}

	public boolean isFull() {
		return writePosition == buffer.capacity();
	}

	public void compact() {
		if (readPosition > 0) {
			buffer.compact();
			writePosition -= readPosition;
			readPosition = 0;
		}
	}

	public int getRemaining() {
		return buffer.capacity() - writePosition;
	}
}
